/* Standard includes */
#include <string.h>
#include <stdlib.h>

/* Libs */
#include <zzip/lib.h>

/* Amazo includes */
#include "include/logger.h"

int last_buf_size = 0;

unsigned char * load_file_from_archive(ZZIP_DIR *archive, char *filename)
{	
	unsigned char * result = NULL;
	unsigned char * temp = NULL;
	int data_length = 0;
	
	/* Open the archive and the file */
	ZZIP_FILE* fp = zzip_file_open(archive, filename, 0);
	if (fp) {
		/* Read data in chunks of 4096 and store in memory */
		#define BUF_SIZE 4096
		
		char buf[BUF_SIZE];
		zzip_size_t bytes_read;
		
		while((bytes_read = zzip_file_read(fp, buf, BUF_SIZE))) {
			
			/* Copy the existing data to a temp memory address */
			if(data_length) {
				temp = malloc(data_length);
				memcpy(temp, result, data_length);
			}
			
			/* Allocate space to hold the old + new data
			    Append a null terminator to the end of data,
			    in case the file is a text file. */
			if(result)
				free(result);
			result = malloc(data_length + bytes_read + 1); 
			
			/* Return the old data and add the new data on top */
			if(temp)
				memcpy(result, temp, data_length);
			memcpy(result+data_length, buf, bytes_read);
			memset(result+data_length+bytes_read, '\0', 1);

			/* The temporary buffer is not required anymore */
			if(data_length)
				free(temp);
			data_length += bytes_read;
		}
		last_buf_size = data_length;
	}
	else {
		amazolog("*** ERROR: The archive does not contain the file '%s' ***\n", filename);
		return NULL;
	}
	zzip_file_close(fp);
	return result;
}
